package com.atguigu.daijia.order.service.impl;

import com.atguigu.daijia.common.constant.RedisConstant;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.model.entity.order.*;
import com.atguigu.daijia.model.enums.OrderStatus;
import com.atguigu.daijia.model.form.order.OrderInfoForm;
import com.atguigu.daijia.model.form.order.StartDriveForm;
import com.atguigu.daijia.model.form.order.UpdateOrderBillForm;
import com.atguigu.daijia.model.form.order.UpdateOrderCartForm;
import com.atguigu.daijia.model.vo.order.CurrentOrderInfoVo;
import com.atguigu.daijia.order.mapper.OrderBillMapper;
import com.atguigu.daijia.order.mapper.OrderInfoMapper;
import com.atguigu.daijia.order.mapper.OrderProfitsharingMapper;
import com.atguigu.daijia.order.mapper.OrderStatusLogMapper;
import com.atguigu.daijia.order.service.OrderInfoService;
import com.atguigu.daijia.order.service.OrderMonitorService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Override
    public Long submitOrder(OrderInfoForm orderInfoForm) {
        //常见订单对象
        OrderInfo orderInfo = new OrderInfo();
        //设置订单属性
        BeanUtils.copyProperties(orderInfoForm,orderInfo);
        String orderNo = UUID.randomUUID().toString().replaceAll("-","");
        orderInfo.setOrderNo(orderNo);
        orderInfo.setStatus(1);
        //保存订单
        this.save(orderInfo);
        //保存订单状态
        savelog(orderInfo.getId(),orderInfo.getStatus());
        //如果接单了，需要修改订单的状态
        redisTemplate.opsForValue().set(RedisConstant.ORDER_ACCEPT_MARK,"0",RedisConstant.ORDER_ACCEPT_MARK_EXPIRES_TIME, TimeUnit.MINUTES);
        return orderInfo.getId();
    }

    @Override
    public Integer getOrderStatus(Long orderId) {
        LambdaQueryWrapper<OrderInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderInfo::getId,orderId);
        lambdaQueryWrapper.select(OrderInfo::getStatus);
        OrderInfo orderInfo = this.getOne(lambdaQueryWrapper);
        if (orderInfo == null){
            return OrderStatus.NULL_ORDER.getStatus();
        }
        return orderInfo.getStatus();
    }

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public Boolean robNewOrder(Long driverId, Long orderId) {
        //如果抢单成功则需要将redis中的数据删除
        if (!redisTemplate.hasKey(RedisConstant.ORDER_ACCEPT_MARK)){
            throw new GuiguException(ResultCodeEnum.COB_NEW_ORDER_FAIL);
        }
        //初始化redisson分布式锁
        RLock lock = redissonClient.getLock(RedisConstant.ROB_NEW_ORDER_LOCK + orderId);
        //加锁，两个参数,等待时间，加锁时间
        try {
            boolean flag = lock.tryLock(RedisConstant.ROB_NEW_ORDER_LOCK_WAIT_TIME, RedisConstant.ROB_NEW_ORDER_LOCK_LEASE_TIME, TimeUnit.SECONDS);
            //判断是否获取锁成功
            if (flag){
                //为了防止重复抢单需要在对redis中的“允许重复这个key”是否可以抢单
                if (!redisTemplate.hasKey(RedisConstant.ORDER_ACCEPT_MARK)){
                    throw new GuiguException(ResultCodeEnum.COB_NEW_ORDER_FAIL);
                }
            }
            //如果抢单成功，修改订单的司机Id
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setId(orderId);
            orderInfo.setStatus(OrderStatus.ACCEPTED.getStatus());
            orderInfo.setAcceptTime(new Date());
            orderInfo.setDriverId(driverId);
            int row = orderInfoMapper.updateById(orderInfo);
            if (row!=1){
                throw new GuiguException(ResultCodeEnum.COB_NEW_ORDER_FAIL);
            }
            this.savelog(orderId,orderInfo.getStatus());
            redisTemplate.delete(RedisConstant.ORDER_ACCEPT_MARK);
        } catch (InterruptedException e) {
            throw new GuiguException(ResultCodeEnum.COB_NEW_ORDER_FAIL);
        }finally {
            //打开锁
            if (lock.isLocked()){
                lock.unlock();
            }
        }
        return true;
    }

    @Override
    public CurrentOrderInfoVo searchCustomerCurrentOrder(Long userId) {
        //需要封装用户条件
        LambdaQueryWrapper<OrderInfo> qw = new LambdaQueryWrapper<>();
        qw.eq(OrderInfo::getCustomerId,userId);
        //乘客端订单已经支付完成，需要将所有状态都进行封装查询
        Integer[] statusList = {
                OrderStatus.ACCEPTED.getStatus(),
                OrderStatus.DRIVER_ARRIVED.getStatus(),
                OrderStatus.UPDATE_CART_INFO.getStatus(),
                OrderStatus.START_SERVICE.getStatus(),
                OrderStatus.END_SERVICE.getStatus(),
                OrderStatus.UNPAID.getStatus(),
        };
        qw.in(OrderInfo::getStatus,statusList);
        qw.orderByDesc(OrderInfo::getId);
        qw.last("limit 1");
        OrderInfo orderInfo = orderInfoMapper.selectOne(qw);
        //判断订单是否存在，如果订单存在则封装用户当前订单即可
        CurrentOrderInfoVo currentOrderInfoVo = new CurrentOrderInfoVo();
        if (orderInfo != null){
            currentOrderInfoVo.setStatus(orderInfo.getStatus());
            currentOrderInfoVo.setOrderId(orderInfo.getId());
            currentOrderInfoVo.setIsHasCurrentOrder(true);
        }else {
            currentOrderInfoVo.setIsHasCurrentOrder(false);
        }
        return currentOrderInfoVo;
    }

    @Override
    public CurrentOrderInfoVo searchDriverCurrentOrder(Long driverId) {
        //需要封装用户条件
        LambdaQueryWrapper<OrderInfo> qw = new LambdaQueryWrapper<>();
        qw.eq(OrderInfo::getCustomerId,driverId);
        //乘客端订单已经支付完成，需要将所有状态都进行封装查询
        Integer[] statusList = {
                OrderStatus.ACCEPTED.getStatus(),
                OrderStatus.DRIVER_ARRIVED.getStatus(),
                OrderStatus.UPDATE_CART_INFO.getStatus(),
                OrderStatus.START_SERVICE.getStatus(),
                OrderStatus.END_SERVICE.getStatus(),
                OrderStatus.UNPAID.getStatus(),
        };
        qw.in(OrderInfo::getStatus,statusList);
        qw.orderByDesc(OrderInfo::getId);
        qw.last("limit 1");
        OrderInfo orderInfo = orderInfoMapper.selectOne(qw);
        //判断订单是否存在，如果订单存在则封装用户当前订单即可
        CurrentOrderInfoVo currentOrderInfoVo = new CurrentOrderInfoVo();
        if (orderInfo != null){
            currentOrderInfoVo.setStatus(orderInfo.getStatus());
            currentOrderInfoVo.setOrderId(orderInfo.getId());
            currentOrderInfoVo.setIsHasCurrentOrder(true);
        }else {
            currentOrderInfoVo.setIsHasCurrentOrder(false);
        }
        return currentOrderInfoVo;
    }

    @Override
    public Boolean driverArriveStartLocation(Long orderId, Long driverId) {
        //需要根据订单Id和司机查询修改订单状态
        LambdaQueryWrapper<OrderInfo> qr = new LambdaQueryWrapper<>();
        qr.eq(OrderInfo::getId,orderId);
        qr.eq(OrderInfo::getDriverId,driverId);
        //修改订单的状态
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setStatus(OrderStatus.DRIVER_ARRIVED.getStatus());
        orderInfo.setArriveTime(new Date());
        int row = orderInfoMapper.update(orderInfo, qr);
        if (row==1){
            savelog(orderId,OrderStatus.DRIVER_ARRIVED.getStatus());
        }else {
            throw new GuiguException(ResultCodeEnum.UPDATE_ERROR);
        }
        return true;
    }

    @Override
    public Boolean updateOrderCart(UpdateOrderCartForm updateOrderCartForm) {
        //需要根据订单Id和司机查询修改订单状态
        LambdaQueryWrapper<OrderInfo> qr = new LambdaQueryWrapper<>();
        qr.eq(OrderInfo::getId,updateOrderCartForm.getOrderId());
        qr.eq(OrderInfo::getDriverId,updateOrderCartForm.getDriverId());
        //修改订单的状态
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(updateOrderCartForm,orderInfo);
        orderInfo.setStatus(OrderStatus.UPDATE_CART_INFO.getStatus());
        int row = orderInfoMapper.update(orderInfo, qr);
        if (row==1){
            savelog(updateOrderCartForm.getOrderId(),OrderStatus.UPDATE_CART_INFO.getStatus());
        }else {
            throw new GuiguException(ResultCodeEnum.UPDATE_ERROR);
        }
        return true;
    }

    @Autowired
    private OrderMonitorService orderMonitorService;

    @Override
    public Boolean startDrive(StartDriveForm startDriveForm) {
        LambdaQueryWrapper<OrderInfo> qr = new LambdaQueryWrapper<>();
        qr.eq(OrderInfo::getId,startDriveForm.getOrderId());
        qr.eq(OrderInfo::getDriverId,startDriveForm.getDriverId());
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setStatus(OrderStatus.START_SERVICE.getStatus());
        orderInfo.setStartServiceTime(new Date());
        //更新订单
        int row = orderInfoMapper.update(orderInfo, qr);
        if (row==1){
            savelog(startDriveForm.getOrderId(),OrderStatus.START_SERVICE.getStatus());
        }else {
            throw new GuiguException(ResultCodeEnum.UPDATE_ERROR);
        }
        //记录订单数据
        OrderMonitor orderMonitor = new OrderMonitor();
        orderMonitor.setOrderId(startDriveForm.getOrderId());
        orderMonitorService.save(orderMonitor);
        return true;
    }

    @Override
    public Long getOrderNumByTime(String startTime, String endTime) {
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(OrderInfo::getStartServiceTime, startTime);
        queryWrapper.lt(OrderInfo::getStartServiceTime, endTime);
        Long count = orderInfoMapper.selectCount(queryWrapper);
        return count;
    }

    @Autowired
    private OrderBillMapper orderBillMapper;

    @Autowired
    private OrderProfitsharingMapper orderProfitsharingMapper;

    @Override
    public Boolean endDrive(UpdateOrderBillForm updateOrderBillForm) {
        //更新订单信息，需要先查询出订单的信息，然后再更新
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderInfo::getId, updateOrderBillForm.getOrderId());
        queryWrapper.eq(OrderInfo::getDriverId, updateOrderBillForm.getDriverId());
        //更新字段
        OrderInfo updateOrderInfo = new OrderInfo();
        updateOrderInfo.setStatus(OrderStatus.END_SERVICE.getStatus());
        updateOrderInfo.setRealAmount(updateOrderBillForm.getTotalAmount());
        updateOrderInfo.setFavourFee(updateOrderBillForm.getFavourFee());
        updateOrderInfo.setEndServiceTime(new Date());
        updateOrderInfo.setRealDistance(updateOrderBillForm.getRealDistance());
        //只能更新自己的订单
        int row = orderInfoMapper.update(updateOrderInfo, queryWrapper);
        if(row == 1) {
            //记录日志
            this.savelog(updateOrderBillForm.getOrderId(), OrderStatus.END_SERVICE.getStatus());

            //插入实际账单数据
            OrderBill orderBill = new OrderBill();
            BeanUtils.copyProperties(updateOrderBillForm, orderBill);
            orderBill.setOrderId(updateOrderBillForm.getOrderId());
            orderBill.setPayAmount(orderBill.getTotalAmount());
            orderBillMapper.insert(orderBill);

            //插入分账信息数据
            OrderProfitsharing orderProfitsharing = new OrderProfitsharing();
            BeanUtils.copyProperties(updateOrderBillForm, orderProfitsharing);
            orderProfitsharing.setOrderId(updateOrderBillForm.getOrderId());
            orderProfitsharing.setRuleId(updateOrderBillForm.getProfitsharingRuleId());
            orderProfitsharing.setStatus(1);
            orderProfitsharingMapper.insert(orderProfitsharing);
        } else {
            throw new GuiguException(ResultCodeEnum.UPDATE_ERROR);
        }
        return true;
    }


    @Autowired
    private OrderStatusLogMapper orderStatusLogMapper;

    private void savelog(Long orderId,Integer status) {
        OrderStatusLog orderStatusLog = new OrderStatusLog();
        orderStatusLog.setOrderId(orderId);
        orderStatusLog.setOrderStatus(status);
        orderStatusLog.setOperateTime(new Date());
        orderStatusLog.setCreateTime(new Date());
        orderStatusLogMapper.insert(orderStatusLog);
    }





















}
